package com.bkgc.manage.shiro;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bkgc.common.utils.HttpRequest;
import com.bkgc.manage.consumer.ShiroService;
import com.bkgc.manage.bean.OauthRole;
import com.bkgc.manage.bean.PermissionMenu;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gmg on 2017/9/27.
 */
public class MyRelam extends AuthorizingRealm{

    @Autowired
    private ShiroService shiroService;

    @Value("${oauth_url}")
    private String oauth_url;
    Logger logger= LoggerFactory.getLogger(this.getClass());
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        try{
            logger.info("doGetAuthenticationInfo "+authenticationToken.toString());
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            String username=token.getUsername();
            String password=String.valueOf(token.getPassword());
            String response = HttpRequest.sendPost(oauth_url+"/oauth/user/login", "username="+username+"&password="+password);
            JSONObject jsonObject = JSON.parseObject(response);
            int code = jsonObject.getIntValue("code");
            if (code == 1000) {
                //设置用户session
                Session session = SecurityUtils.getSubject().getSession();
                session.setAttribute("roleId",jsonObject.getJSONObject("data").getString("roleid"));
                return new SimpleAuthenticationInfo(username,password,getName());
            } else {
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("doGetAuthorizationInfo+"+principals.toString());
        String currentUsername = (String)super.getAvailablePrincipal(principals);
        List<String> roleList = new ArrayList<>();
        List<String> permissionList = new ArrayList<String>();
        clearCached();
        Session session = SecurityUtils.getSubject().getSession();
        String roleId=String.valueOf(session.getAttribute("roleId"));
            //获取当前登录用户的角色
        if(roleId!=null) {
            OauthRole role = shiroService.getRoleById(roleId);
            if (role == null) {
                throw new AuthorizationException();
            }else{
                if (role.getDeleted() == 0) {
                    roleList.add(role.getName());
                    //实体类Role中包含有角色权限的实体类信息
                    if (null != role.getPermissions() && role.getPermissions().size() > 0) {
                        //获取权限
                        for (PermissionMenu pmss : role.getPermissions()) {
                            if (!StringUtils.isEmpty(pmss.getPermission())) {
                                permissionList.add(pmss.getPermission());
                            }
                        }
                    }
                }
            }
        }else{
            throw new AuthorizationException();
        }
        //为当前用户设置角色和权限
       // SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        simpleAuthorInfo.addRoles(roleList);
        simpleAuthorInfo.addStringPermissions(permissionList);
        return simpleAuthorInfo;
    }

    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCachedAuthorizationInfo(principals);
    }
}
